﻿<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title>Most frequent number</title>
    <link href="Styles/js-console.css" rel="stylesheet" />
    <script src="Scripts/isValidInput.js"></script>
</head>
<body>
    <div id="task">
        <p>
            Write a program that finds the most frequent number in an array. Example:
	        {4, 1, 1, 4, 2, 3, 4, 4, 1, 2, 4, 9, 3} -> 4 (5 times)
        </p>
        <a href="5.html">
            <button>Previous task</button></a>
        <a href="7.html">
            <button>Next task</button></a>
    </div>

    <br />
    <label for="array">Enter array elements (separated by intervals):</label>
    <input id="array" type="text" />
    <button onclick="FindMostFrequent()">Sort</button>

    <div id="js-console"></div>
    <script src="Scripts/js-console.js"></script>

    <script>
        function FindMostFrequent() {
            //read input
            var stringArray = document.getElementById("array").value.split(' ');

            //parse input
            var numbers = new Array(stringArray.length);
            for (var i = 0; i < stringArray.length; i++) {
                numbers[i] = parseInt(stringArray[i]);
            }

            //solution
            //sorting array
            numbers.sort(orderBy);

            //find maximal sequence of equal elements using task 3
            var bestElement;
            var checker = numbers[0];
            var currentSequenceLength = 1;
            var maxSequenceLength = 0;

            for (var i = 1; i < numbers.length; i++) {
                if (numbers[i] == checker) {
                    currentSequenceLength++;
                }
                else {
                    if (currentSequenceLength > maxSequenceLength) {
                        maxSequenceLength = currentSequenceLength;
                        bestElement = checker;
                    }
                    currentSequenceLength = 1;
                    checker = numbers[i]
                }
            }
            if (currentSequenceLength > maxSequenceLength) { // this check is missed by for checks
                maxSequenceLength = currentSequenceLength;
                bestElement = checker;
            }

            //print result
            jsConsole.writeLine(bestElement + " (" + maxSequenceLength + " times)");
        }

        function orderBy(a, b) {
            return (a == b) ? 0 : a > b ? 1 : -1;
        }
    </script>
</body>
</html>
